import * as zipper from "zip-local";
import { BasePack } from "../BasePack";
import { IPackageOptions } from "../IPack";
import { cpDir, cpFile, mkdirsSync } from "../../utils/CpFile";
import { join } from "path";
import { readFileSync, writeFileSync, statSync, readdirSync, existsSync, copyFileSync } from "fs";
import { paserIndexJs } from "../../utils/PaserFile";
import { PackMgr } from "../PackMgr";

export class WebPack extends BasePack {

    protected _enginePluginVers = [];// 当前实现的引擎版本

    constructor(packProjectJsonName: string) {
        super(packProjectJsonName);
        this._projectConfigFile = '';
        this._layaEnginePlugins = [
        ];
    }

    packProject(mode = 'dev') {
        this._mode = mode;

        let jsonUrl = join(process.cwd(), this._packProjectJsonName)
        if (!existsSync(jsonUrl)) {
            console.log('no layapp init config, please use: layapp init projname wx');
            PackMgr.inst.packNext();
            return;
        }
        let cfgStr = readFileSync(jsonUrl).toString();
        this._projCfg = JSON.parse(cfgStr);
        let plat = this._plat = this._projCfg.init.plat;

        console.log('start package: =======', this._plat);

        let po: IPackageOptions = this._packOpt = this._projCfg[mode]['packageOptions'];
        // 如果导出目录中，已经存在 project.config.json 则跳过初始化过程
        let projUrl = join(po.outputPath, `${plat}/${plat}game`)
        if (existsSync(projUrl)) {
            this._startPack(po);
        } else {
            this._initProject()
        }

    }

    protected _initProject() {
        let out = join(this._packOpt.outputPath, `${this._plat}/${this._plat}game`);
        mkdirsSync(out);

        this._startPack(this._packOpt);
    }

    protected _startPack(packOpt: IPackageOptions) {
        this._minigamePath = join(this._packOpt.outputPath, `${this._plat}/${this._plat}game`);
        this._setIndexHtml()
        this._setIndexJs()
        // this._setGameConfig();
        this._copyJs()
    }

    protected _setIndexHtml() {
        let fromIndex = join(this._packOpt.projectBin, 'index.html');
        if (existsSync(fromIndex)) {
            let outIndex = join(this._packOpt.outputPath, `${this._plat}/${this._plat}game`, 'index.html');
            copyFileSync(fromIndex, outIndex);
        }
        let fromLogin = join(this._packOpt.projectBin, 'login.html');
        if (existsSync(fromLogin)) {
            let outLogin = join(this._packOpt.outputPath, `${this._plat}/${this._plat}game`, 'login.html');
            copyFileSync(fromLogin, outLogin);
        }
    }

    protected _setGameConfig(configUrl?: string) {
        let config: any = this._projCfg[this._mode]['config'];

        if (!config) {
            config = {};
            return;
        }
        let txt = `window.config = ${JSON.stringify(config)};\n`;
        let po = this._projCfg[this._mode]['packageOptions'];
        configUrl = configUrl ? configUrl : join(po.outputPath, `${this._plat}/${this._plat}game`, 'config.js');
        writeFileSync(configUrl, txt);
    }
    protected _copyJs() {
        let fromIndex = join(this._packOpt.projectBin, 'index.js');
        let { jslist } = paserIndexJs(fromIndex, this._layaEnginePlugins, !!this._packOpt.enginePlugin);

        // 将index中的需要用到的js拷贝到wxgame项目中
        let from: string[] = [];
        let to: string[] = [];
        jslist.forEach(url => {
            from.push(join(this._packOpt.projectBin, url))
            let libUrl = join(this._minigamePath, url);
            to.push(libUrl);
        });

        cpFile(from, to, () => {

            if (this._packOpt.skipResCheck) {
                console.log(this._mode + ' pack over');
                this._setGameConfig();
                this._packOver()
                return;
            } else {
                this._resPath = this._packOpt.resPath;
                this._cpResIndex = 0;
                // delDir(join(this._minigamePath, 'res'));// 拷贝资源文件前先删除原有res目录
                this._setGameConfig();
                this._cpRes();
            }

        }, !this._packOpt.skipCodeUglify, { file: this._layaEnginePlugins })
    }

    protected _setIndexJs() {
        // 修改index.js
        let fromIndex = join(this._packOpt.projectBin, 'index.js');
        let { index_txt, plugin_txt, plugin_list } = paserIndexJs(fromIndex, this._layaEnginePlugins, !!this._packOpt.enginePlugin);
        let outIndex = join(this._packOpt.outputPath, `${this._plat}/${this._plat}game`, 'index.js');

        let indexInjectionStr = this._projCfg[this._mode]['indexInjection'];
        if (indexInjectionStr) {
            index_txt = indexInjectionStr + '\n' + index_txt;
        }
        writeFileSync(outIndex, index_txt);

    }

}